package com.eclink.asset.asset.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.eclink.asset.asset.domain.dao.AssetInventoryRelItem;
import com.eclink.asset.asset.domain.dao.FlowApply;
import com.eclink.asset.asset.domain.dto.AssetInventoryDTO;
import com.eclink.asset.asset.domain.dto.AssetInventoryOperateDTO;
import com.eclink.asset.common.domain.dto.CommonUserDTO;
import com.eclink.asset.domain.CommonUser;
import com.eclink.asset.domain.dto.AssetInventorySaveDTO;
import com.eclink.asset.domain.query.AssetInventoryQuery;
import com.eclink.asset.service.AssetCategoryService;
import com.eclink.asset.service.AssetInventoryDetailService;
import com.eclink.asset.service.AssetInventoryService;
import com.eclink.asset.service.CommonUserService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 资产入库Controller
 *
 * @author zcc
 * @date 2024-06-04
 */
@Api(tags ="资产盘点接口")
@RestController
@RequestMapping("/asset/inventory")
public class AssetInventoryController extends BaseController {

    @Resource
    private AssetInventoryService assetInventoryService;

    @Resource
    private AssetInventoryDetailService detailService;

    @Resource
    private CommonUserService commonUserService;

    @Resource
    private AssetCategoryService assetCategoryService;
    @Autowired
    private AssetInventoryDetailService assetInventoryDetailService;

    private List<CommonUserDTO> getManagerUser(String userId) {
        String[] segs = userId.split(",");
        List<CommonUserDTO> users = new ArrayList<>();
        for (String seg : segs) {
            Long uId = Long.valueOf(seg);
            CommonUserDTO u = commonUserService.getUserSimpleById(uId);
            users.add(u);
        }
        return users;
    }

    @ApiOperation("查询列表")
    @PostMapping("/list")
    public ResponseEntity<Page<AssetInventoryDTO>> list(@RequestBody AssetInventoryQuery query, Pageable page) {
        List<FlowApply> list = assetInventoryService.selectList(query, page);
        List<AssetInventoryDTO> res = new ArrayList<>();
        Long currentUserId = SecurityUtils.getUserId();
        boolean isAdmin = SecurityUtils.isAdmin(currentUserId);
        for(FlowApply assetInventory : list){

            AssetInventoryDTO dto = new AssetInventoryDTO();

            Map<String,Object> formData = JSONObject.parseObject(assetInventory.getFormData());
            String userId = (String) formData.get("userId");
            List<CommonUserDTO> userList = getManagerUser(userId);
            dto.setManagerName(userList.stream().map(CommonUserDTO::getNickName).collect(Collectors.joining(",")));
            res.add(dto);
            BeanUtil.copyProperties(assetInventory, dto);

            if (dto.getCreateUserId()!=null && dto.getCreateUserId() > 0) {
                dto.setCreateUserName(commonUserService.getNickNameById(dto.getCreateUserId()));
            }
            if (isAdmin) {
                dto.setCanDelete(true);
                dto.setCanEdit(true);
            }
        }
        long total = ( (com.github.pagehelper.Page) list ).getTotal();
        return ResponseEntity.ok(new PageImpl<>(res, page, total));
    }

    @ApiOperation("保存")
    @PostMapping("/save")
    public ResponseEntity<Integer> save(@RequestBody AssetInventorySaveDTO saveDTO) {
        assetInventoryService.save(saveDTO);
        return ResponseEntity.ok(1);
    }

    @ApiOperation("查询列表")
    @PostMapping("/detail/list/{parentId}")
    public ResponseEntity<Page<AssetInventoryRelItem>> detailList(@RequestBody AssetInventoryQuery query, Pageable page, @PathVariable String parentId) {
        List<AssetInventoryRelItem> list = detailService.selectListDetailItem(query, page, parentId);
        for(AssetInventoryRelItem item : list){
            if (item.getCategoryId()!=null && item.getCategoryId() != 0) {
                item.setCategoryName(assetCategoryService.selectNameById(item.getCategoryId()));
            }
            if (item.getUserId()!=null && item.getUserId() != 0) {
                item.setUserName(commonUserService.getNickNameById(item.getUserId()));
            }
            if (item.getAdminId()!=null && item.getAdminId() != 0) {
                item.setUserName(commonUserService.getNickNameById(item.getAdminId()));
            }
        }
        long total = ( (com.github.pagehelper.Page) list ).getTotal();
        return ResponseEntity.ok(new PageImpl<>(list, page, total));
    }


    @ApiOperation("提交盘点结果前的提示")
    @GetMapping("/getTipContent/{id}")
    public ResponseEntity<Map<String, Integer>> getTipContent(@PathVariable String id) {
        return ResponseEntity.ok(assetInventoryService.getNumMap(id));
    }

    @ApiOperation("提交盘点")
    @PostMapping("/sub/{id}")
    public ResponseEntity<Integer> sub(@PathVariable String id) {
        assetInventoryService.sub(id);
        return ResponseEntity.ok(1);
    }

    @ApiOperation("提交盘点")
    @GetMapping("/result/{id}")
    public ResponseEntity<Map<String, Integer>> getResult(@PathVariable String id) {
        return ResponseEntity.ok(assetInventoryService.getNumMap(id));
    }

    @ApiOperation("删除")
    @DeleteMapping("/{ids}")
    public ResponseEntity<Integer> remove(@PathVariable Long[] ids) {
        assetInventoryService.deleteByIds(ids);
        return ResponseEntity.ok(1);
    }

    @ApiOperation("盘点")
    @PutMapping("/inventory")
    public ResponseEntity<Integer> inventory(@RequestBody AssetInventoryOperateDTO dto) {
        detailService.inventory(dto);
        return ResponseEntity.ok(1);
    }

    @ApiOperation("详情")
    @GetMapping("/detail/{id}")
    public ResponseEntity<FlowApply> detail(@PathVariable String id) {
        return ResponseEntity.ok(assetInventoryService.getById(id));
    }

    @ApiOperation("盘盈详情")
    @GetMapping("/getProfitDetail/{id}")
    public ResponseEntity<AssetInventoryRelItem> getProfitDetail(@PathVariable Long id) {
        return ResponseEntity.ok(detailService.getProfitDetail(id));
    }

    @ApiOperation("增加盘盈")
    @PostMapping("/addProfit")
    public ResponseEntity<Integer> addProfit(@RequestBody AssetInventoryRelItem saveDTO) {
        detailService.addProfit(saveDTO);
        return ResponseEntity.ok(1);
    }

    @ApiOperation("修改盘盈")
    @PutMapping("/updateProfit")
    public ResponseEntity<Integer> updateProfit(@RequestBody AssetInventoryRelItem saveDTO) {
        detailService.updateProfit(saveDTO);
        return ResponseEntity.ok(1);
    }

    @ApiOperation("修改盘盈")
    @DeleteMapping("/delProfit/{ids}")
    public ResponseEntity<Integer> delProfit(@PathVariable Long[] ids) {

        detailService.delProfit(ids);
        return ResponseEntity.ok(1);
    }


    @ApiOperation("自动盘点")
    @PutMapping("/autoInventory")
    public ResponseEntity<Integer> autoInventory(@RequestBody List<String> rfidList) {
        detailService.autoInventory(rfidList);
        return ResponseEntity.ok(1);
    }

    @ApiOperation("自动盘点")
    @PutMapping("/finishRelItem/{id}")
    public ResponseEntity<Integer> finishRelItem(@PathVariable Long id) {
        detailService.finishRelItem(id);
        return ResponseEntity.ok(1);
    }





}
